import { showMsg } from './showMsg.js'

const axios = require('axios')
const { config } = require('../../config.js')


/**
   * 获取临时上传 Token
   * @param {string} token - Bearer Token
   * @param {number} num - 生成数量（最大 100）
   * @param {number} seconds - 有效期（秒，最大 2626560 秒，即一个月）
   * @returns {Promise<Object[]>} - 返回的临时 Token 列表
   */
export const getUploadTokens = async(token = config.helloToken, num = 1, seconds = 3600) =>
{
  const baseUrl = 'https://www.helloimg.com/api/v1'
  const url = `${baseUrl}/images/tokens`

  try
  {
    const response = await axios.post(url, { num, seconds }, {
      headers: {
        Authorization: `Bearer ${token}`,
        Accept: 'application/json'
      }
    })

    if (response.data.status && response.data.data.tokens)
      return response.data.data.tokens
    else
      throw new Error(response.data.message || '上传凭证获取失败')
  }
  catch (error)
  {
    showMsg('请求失败', error.response?.data || error.message, 'error')
    throw error
  }
}

/**
   * 上传图片
   * @param {string} token - Bearer Token
   * @param {File} file - 图片文件对象
   * @param {string} uploadToken - 临时上传 Token
   * @param {Object} options - 其他可选参数
   * @param {number} [options.permission=1] - 权限（1=公开，0=私有，默认公开）
   * @param {number} [options.strategy_id] - 储存策略 ID
   * @param {number} [options.album_id] - 相册 ID
   * @param {string} [options.expired_at] - 图片过期时间（格式：yyyy-MM-dd HH:mm:ss）
   * @returns {Promise<Object>} - 返回的上传结果
   */
export const uploadImage = async(token, file, uploadToken, options = {}) =>
{
  const baseUrl = 'https://www.helloimg.com/api/v1'
  const url = `${baseUrl}/upload`

  const formData = new FormData()
  formData.append('file', file) // 必传字段
  formData.append('token', uploadToken) // 必传字段

  if (options.permission !== undefined) formData.append('permission', options.permission)
  if (options.strategy_id) formData.append('strategy_id', options.strategy_id)
  if (options.album_id) formData.append('album_id', options.album_id)
  if (options.expired_at) formData.append('expired_at', options.expired_at)

  try
  {
    const response = await axios.post(url, formData, {
      headers: {
        Authorization: `Bearer ${token}`,
        Accept: 'application/json',
        'Content-Type': 'multipart/form-data'
      }
    })
    if (response.data.status && response.data.data)
      return response.data.data
    else
      throw new Error(response.data.message || '图片上传失败')
  }
  catch (error)
  {
    showMsg('图片上传失败', error.response?.data || error.message, 'error')
    throw error
  }
}

